/**
 * FileName: SafePhoto.java
 * @Description: TODO(用一句话描述该文件做什么)
 * All rights Reserved, Designed By 21winmess
 * Copyright: Copyright(C) 2010-2011 
 * Company 21winmess DaLian LTD.
 * @author: Matrix xu
 * @version V2.0
 * Createdate: 2012-12-13 下午2:54:58
 *
 * Modification History:
 * Date Author Version Discription
 * -----------------------------------------------------------------------------------
 * 2012-12-13 Qute_Android2.0
 * Why & What is modified: <修改原因描述>
 */
package com.me.safebox.ui.photo;

import java.util.List;
import java.util.concurrent.Callable;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;

import com.me.safebox.R;
import com.me.safebox.data.SafeFile;
import com.me.safebox.data.SafeboxDao;
import com.me.safebox.service.FileConfig;
import com.me.safebox.service.FileDecryptTask;
import com.me.safebox.service.FileHandleThreadPool;
import com.me.safebox.service.IFuture;
import com.me.safebox.ui.MainApp;
import com.me.safebox.ui.adapter.SafePhotoAdapter;

/**
 * @ClassName: SafePhoto
 * @Description:TODO(这里用一句话描述这个类的作用)
 * @author: Matrix
 * @date: 2012-12-13 下午2:54:58
 * 
 */
public class SafePhoto extends Activity implements OnClickListener {

	private static final String TAG = "SafePhoto";

	private GridView mGridView = null;

	private SafePhotoAdapter mSafePhotoAdapter = null;

	private SelectAllListener mOnSelectAllListener = null;

	private long folderId;

	private TextView backView = null;

	private Button mSelectBtn = null;

	private Button decryptBtn = null;

	private boolean allSelected = false;

	private final static int QUERY_FILES = 1;

	private ProgressDialog mProgressDialog = null;

	private FileHandleThreadPool<Callable<IFuture>> mFileHandleThreadPool = FileHandleThreadPool.getInstance();

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onCreate(android.os.Bundle)
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.layout_photo);
		mGridView = (GridView) findViewById(R.id.photo_gridview);
		mSelectBtn = (Button) findViewById(R.id.select_btn);
		decryptBtn = (Button) findViewById(R.id.decry_btn);
		backView = (TextView) findViewById(R.id.back_tv);
		backView.setOnClickListener(this);
		mSelectBtn.setOnClickListener(this);
		decryptBtn.setOnClickListener(this);
		mSafePhotoAdapter = new SafePhotoAdapter(this, MainApp.getFinalBitmap());
		mOnSelectAllListener = mSafePhotoAdapter.onSelectAllListener;
		mGridView.setAdapter(mSafePhotoAdapter);
		folderId = getIntent().getLongExtra("folderId", 0L);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onResume()
	 */
	@Override
	protected void onResume() {
		super.onResume();
		this.getFile();
	}

	private void getFile() {
		/**
		 * 扫描当前文件夹
		 */
		// Thread fileScanThread = new Thread() {
		// @Override
		// public void run() {
		List<SafeFile> list = new SafeboxDao().getSafeFile(folderId, FileConfig.FILE_TYPE_IMAGE);
		Log.i(TAG, "list size:" + list.size());
		Message msg = mHandler.obtainMessage();
		msg.obj = list;
		msg.what = QUERY_FILES;
		mHandler.sendMessage(msg);
		// }
		// };
		// fileScanThread.start();
	}

	private Handler mHandler = new Handler() {
		private int count = 1;

		@SuppressWarnings("unchecked")
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case QUERY_FILES:
				List<SafeFile> results = (List<SafeFile>) msg.obj;
				mSafePhotoAdapter.setData(results);
				mSafePhotoAdapter.notifyDataSetChanged();

				// 该相册里面没有图片,dialog引导用户立刻添加图片
				if (results.size() == 0) {
					nonePhotoDialog();
				}

				break;
			case FileHandleThreadPool.COUNTING:
				if (mProgressDialog != null) {
					Log.i("filetask", count + "");
					mProgressDialog.setProgress(count++);
				}
				break;
			case FileHandleThreadPool.TASK_FINISH:
				if (mProgressDialog != null) {
					mProgressDialog.dismiss();
					Log.i("filetask", "finish");
					// 解密完成后进入私密相册画面
					Intent intent = new Intent();
					intent.setClass(SafePhoto.this, SafeAlbum.class);
					startActivity(intent);
					finish();
					// getFile();// 刷新本目录
					break;
				}
			}
		}
	};

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onStop()
	 */
	@Override
	protected void onStop() {
		super.onStop();
		if (this.mSafePhotoAdapter != null) {
			mSafePhotoAdapter.clearData();
			mSafePhotoAdapter.clearView();
		}
		MainApp.getFinalBitmap().clearMemeoryCache();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.back_tv:
			Intent intent = new Intent();
			intent.setClass(this, SafeAlbum.class);
			startActivity(intent);
			finish();
			break;
		case R.id.select_btn:
			if (!allSelected) {
				this.mOnSelectAllListener.onSelectAll();
				mSelectBtn.setText("取消");
				allSelected = true;
			} else {
				this.mOnSelectAllListener.onUnSelectAll();
				mSelectBtn.setText("全选");
				allSelected = false;
			}
			break;
		case R.id.decry_btn:
			decryptExecute();
			break;
		}

	}

	private void decryptExecute() {

		int selectObjectSize = mSafePhotoAdapter.getSelectedObject().size();
		if (selectObjectSize == 0) {
			Toast.makeText(this, "请选择需要恢复的图片", Toast.LENGTH_SHORT).show();
			return;
		}
		loadProgressDialog(selectObjectSize);// 加载进度条
		Thread decryThread = new Thread() {// 开启解密线程
			@Override
			public void run() {
				List<SafeFile> fileList = mSafePhotoAdapter.getSelectedObject();
				for (SafeFile SF : fileList) {
					FileDecryptTask decryptTask = new FileDecryptTask(SF);
					mFileHandleThreadPool.setTaskList(decryptTask);
				}
				fileList.clear();
				mFileHandleThreadPool.mhandler = mHandler;
				mFileHandleThreadPool.startDecrypt();
			}
		};
		decryThread.start();
	}

	/**
	 * 弹出进度条
	 * 
	 * @param taskNum
	 */
	public void loadProgressDialog(int taskNum) {
		mProgressDialog = new ProgressDialog(this);
		// 设置进度条风格，风格为长形
		mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		// 设置ProgressDialog 标题
		mProgressDialog.setTitle("提示");
		// 设置ProgressDialog 提示信
		mProgressDialog.setMessage("正在加密文件");
		// 设置ProgressDialog 标题图标
		// mProgressDialog.setIcon(R.drawable.img2);
		mProgressDialog.setMax(taskNum);
		// 设置ProgressDialog 进度条进度
		// mProgressDialog.setProgress(50);
		// 设置ProgressDialog 的进度条是否不明确
		mProgressDialog.setIndeterminate(false);
		// 设置ProgressDialog 是否可以按退回按键取消
		mProgressDialog.setCancelable(true);
		// 让ProgressDialog显示
		mProgressDialog.show();

	}

	protected void nonePhotoDialog() {
		AlertDialog.Builder builder = new Builder(SafePhoto.this);
		builder.setMessage("无图无真相,要立刻添加吗?");
		builder.setTitle("提示");
		builder.setPositiveButton("走你", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();// 去扫描sd卡
				Intent intent = new Intent(SafePhoto.this, MediaScan.class);
				startActivity(intent);
				SafePhoto.this.finish();
			}
		});
		builder.setNegativeButton("算了", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				SafePhoto.this.finish();// 返回私密相册画面
			}
		});
		builder.create().show();
	}
}
